<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Vue3.0——Provide/Inject的妙用 | Tab</title><meta name="keywords" content="Vue"><meta name="author" content="Tab"><meta name="copyright" content="Tab"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Vue3.0——Provide&#x2F;Inject的妙用说起Vue的状态管理工具，应该大部分人都会想到Vuex，毕竟是官方提供的工具，但是都进入Vue3时代了，不会还有人不知道依赖注入吧。为什么会突然提到依赖注入呢？跟状态管理工具有什么关系呢？当然有关系，因为依赖注入在Vue3中可以替代Vuex。我们知道Vue3提供的ref&#x2F;reactive API具有组件解耦的特性，也就是说我们可以在组件之外创建响应">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue3.0——Provide&#x2F;Inject的妙用">
<meta property="og:url" content="https://tabxx.github.io/tab.github.io/2021/05/15/inject/index.html">
<meta property="og:site_name" content="Tab">
<meta property="og:description" content="Vue3.0——Provide&#x2F;Inject的妙用说起Vue的状态管理工具，应该大部分人都会想到Vuex，毕竟是官方提供的工具，但是都进入Vue3时代了，不会还有人不知道依赖注入吧。为什么会突然提到依赖注入呢？跟状态管理工具有什么关系呢？当然有关系，因为依赖注入在Vue3中可以替代Vuex。我们知道Vue3提供的ref&#x2F;reactive API具有组件解耦的特性，也就是说我们可以在组件之外创建响应">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://tabxx.github.io/tab.github.io/2021/05/15/inject/top.jpg">
<meta property="article:published_time" content="2021-05-15T15:07:43.000Z">
<meta property="article:modified_time" content="2021-08-11T11:36:44.308Z">
<meta property="article:author" content="Tab">
<meta property="article:tag" content="Vue">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://tabxx.github.io/tab.github.io/2021/05/15/inject/top.jpg"><link rel="shortcut icon" href="/tab.github.io/images/favicon.ico"><link rel="canonical" href="https://tabxx.github.io/tab.github.io/2021/05/15/inject/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/tab.github.io/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?050bcda3cb147a8c0de1c17a337c5466";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/tab.github.io/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Vue3.0——Provide/Inject的妙用',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-08-11 19:36:44'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
          const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
          const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
          const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified

          if (t === undefined) {
            if (isLightMode) activateLightMode()
            else if (isDarkMode) activateDarkMode()
            else if (isNotSpecified || hasNoSupport) {
              const now = new Date()
              const hour = now.getHours()
              const isNight = hour <= 6 || hour >= 18
              isNight ? activateDarkMode() : activateLightMode()
            }
            window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
              if (saveToLocal.get('theme') === undefined) {
                e.matches ? activateDarkMode() : activateLightMode()
              }
            })
          } else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    })(window)</script><meta name="generator" content="Hexo 5.1.1"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src= "" data-lazy-src="/tab.github.io/images/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/tab.github.io/archives/"><div class="headline">文章</div><div class="length-num">10</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tab.github.io/tags/"><div class="headline">标签</div><div class="length-num">7</div></a></div></div></div><hr/></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/tab.github.io/2021/05/15/inject/top.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/tab.github.io/">Tab</a></span><div id="menus"><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Vue3.0——Provide/Inject的妙用</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-05-15T15:07:43.000Z" title="发表于 2021-05-15 23:07:43">2021-05-15</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-08-11T11:36:44.308Z" title="更新于 2021-08-11 19:36:44">2021-08-11</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.6k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>11分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Vue3.0——Provide/Inject的妙用"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Vue3-0——Provide-Inject的妙用"><a href="#Vue3-0——Provide-Inject的妙用" class="headerlink" title="Vue3.0——Provide/Inject的妙用"></a>Vue3.0——Provide/Inject的妙用</h1><p>说起Vue的状态管理工具，应该大部分人都会想到Vuex，毕竟是官方提供的工具，但是都进入Vue3时代了，不会还有人不知道依赖注入吧。<br>为什么会突然提到依赖注入呢？跟状态管理工具有什么关系呢？<br>当然有关系，因为依赖注入在Vue3中可以替代Vuex。我们知道Vue3提供的ref/reactive API具有组件解耦的特性，也就是说我们可以在组件之外创建响应式数据，这么一来跨组件共享数据的需求就在Vue3新框架内部得到了解决。</p>
<h2 id="Provide-Inject"><a href="#Provide-Inject" class="headerlink" title="Provide / Inject"></a>Provide / Inject</h2><blockquote>
<p>通常，当我们需要从父组件向子组件传递数据时，我们使用 props。如果组件层级比较深，那通过props传递下去会比较麻烦。针对这种情况我们可以使用一对 provide 和 inject。无论组件层次结构有多深，父组件都可以作为其所有子组件的依赖提供者。这个特性有两个部分：父组件有一个 provide 选项来提供数据，子组件有一个 inject 选项来开始使用这些数据。</p>
</blockquote>
<p>Provide / Inject不是什么新的api，在Vue2的时候就已经存在了，只不过在Vue3得到新的应用。这里只做一个简单的介绍，需要详细的介绍见<a target="_blank" rel="noopener" href="https://v3.cn.vuejs.org/guide/component-provide-inject.html#%E5%A4%84%E7%90%86%E5%93%8D%E5%BA%94%E6%80%A7">官方文档</a>。</p>
<p><img src= "" data-lazy-src="components_provide.png" alt="components_provide"></p>
<p>我们理解一些官方给出的示例图，粗暴点来说就是父组件注入一些数据，所有子组件不管嵌套有多深都能直接获取到这些数据。</p>
<h2 id="Provide-Inject-使用方式"><a href="#Provide-Inject-使用方式" class="headerlink" title="Provide / Inject 使用方式"></a>Provide / Inject 使用方式</h2><p>首先在父级组件<code>App.vue</code>注入数据</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;button @click=<span class="string">&quot;editUserInfo&quot;</span>&gt;修改用户信息&lt;/button&gt;</span><br><span class="line">&lt;/template&gt;</span><br><span class="line"></span><br><span class="line">&lt;script lang=<span class="string">&quot;ts&quot;</span>&gt;</span><br><span class="line"><span class="keyword">import</span> &#123; defineComponent, provide, reactive &#125; <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span></span><br><span class="line"><span class="keyword">import</span> Child <span class="keyword">from</span> <span class="string">&#x27;./components/Child.vue&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> defineComponent(&#123;</span><br><span class="line">  name: <span class="string">&#x27;App&#x27;</span>,</span><br><span class="line">  components: &#123;</span><br><span class="line">    Child</span><br><span class="line">  &#125;,</span><br><span class="line">  setup() &#123;</span><br><span class="line">    <span class="keyword">const</span> userInfo = reactive(&#123;</span><br><span class="line">      username: <span class="string">&#x27;&#x27;</span>,</span><br><span class="line">      age: <span class="number">25</span></span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="comment">// 依赖注入</span></span><br><span class="line">    provide(<span class="string">&#x27;userInfo&#x27;</span>, userInfo)</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 修改依赖数据</span></span><br><span class="line">    <span class="keyword">const</span> editUserInfo = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">      userInfo.age = <span class="number">18</span></span><br><span class="line">      userInfo.username = <span class="string">&#x27;Tab&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> &#123; userInfo, editUserInfo &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>

<p>子组件获取注入的数据项</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;div <span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;inject-box&quot;</span>&gt;</span><br><span class="line">    username: &#123;&#123; userInfo.username &#125;&#125;, <span class="attr">age</span>: &#123;&#123; userInfo.age &#125;&#125;</span><br><span class="line">  &lt;/div&gt;</span><br><span class="line">&lt;/template&gt;</span><br><span class="line"></span><br><span class="line">&lt;script lang=<span class="string">&quot;ts&quot;</span>&gt;</span><br><span class="line"><span class="keyword">import</span> &#123; reactive, defineComponent, inject &#125; <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> defineComponent(&#123;</span><br><span class="line">  name: <span class="string">&#x27;Child&#x27;</span>,</span><br><span class="line">  setup: <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 获取注入数据</span></span><br><span class="line">    <span class="keyword">const</span> userInfo = inject(<span class="string">&#x27;userInfo&#x27;</span>);</span><br><span class="line">    <span class="keyword">return</span> &#123; userInfo &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>

<h2 id="Provide-Inject-原理"><a href="#Provide-Inject-原理" class="headerlink" title="Provide / Inject 原理"></a>Provide / Inject 原理</h2><p>provide/inject原理并不复杂，源码的实现也很简单。在看源代码之前，我们可以先看一眼<code>Vue</code>实例上有没有<code>provide</code>和<code>inject</code>的线索。如果<code>Vue</code>实例上就存在相关属性，那么我们就需要从<code>Vue</code>实例的声明开始看源码，否则就可以猜测<code>provide</code>和<code>inject</code>是工具函数，直接搜对应的代码实现即可。</p>
<ol>
<li>万能的<code>console.log</code>查看<code>Vue</code>实例属性。(<code>Vue3</code>不能直接打印<code>this</code>,需要导入<code>getCurrentInstance</code>来获取当前实例)</li>
</ol>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&lt;script lang=<span class="string">&quot;ts&quot;</span>&gt;</span><br><span class="line"><span class="keyword">import</span> &#123; defineComponent, getCurrentInstance &#125; <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> defineComponent(&#123;</span><br><span class="line">  name: <span class="string">&#x27;HelloWorld&#x27;</span>,</span><br><span class="line">  setup: <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 获取当前组件实例并在控制台输出</span></span><br><span class="line">    <span class="keyword">const</span> instance = getCurrentInstance()</span><br><span class="line">    <span class="built_in">console</span>.log(instance)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>

<p>查看控制台日志发现，<code>Vue</code>实例中存在一个<code>provides</code>属性，那就说明<code>Vue</code>实例声明的时候肯定做了一些什么才会有了<code>provide</code>和<code>inject</code>的存在。</p>
<p><img src= "" data-lazy-src="vue_instance.png"></p>
<ol start="2">
<li>然后我们就可以转到源码声明<code>Vue</code>实例的地方，源码位置<code>./packages/runtime-core/src/component.ts</code></li>
</ol>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">createComponentInstance</span>(<span class="params"></span></span></span><br><span class="line"><span class="function"><span class="params">  vnode: VNode,</span></span></span><br><span class="line"><span class="function"><span class="params">  parent: ComponentInternalInstance | <span class="literal">null</span>,</span></span></span><br><span class="line"><span class="function"><span class="params">  suspense: SuspenseBoundary | <span class="literal">null</span></span></span></span><br><span class="line"><span class="function"><span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> <span class="keyword">type</span> = vnode.type <span class="keyword">as</span> ConcreteComponent</span><br><span class="line">  <span class="comment">// appContext继承父组件的上下文，如果是根节点采用从根vnode</span></span><br><span class="line">  <span class="keyword">const</span> appContext =</span><br><span class="line">    (parent ? parent.appContext : vnode.appContext) || emptyAppContext</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> instance: ComponentInternalInstance = &#123;</span><br><span class="line">    uid: uid++,</span><br><span class="line">    vnode,</span><br><span class="line">    <span class="keyword">type</span>,</span><br><span class="line">    parent,</span><br><span class="line">    appContext,</span><br><span class="line">    <span class="comment">// provides 继承父组件的provides</span></span><br><span class="line">    provides: parent ? parent.provides : <span class="built_in">Object</span>.create(appContext.provides),</span><br><span class="line">    <span class="comment">// ................. </span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (__DEV__) &#123;</span><br><span class="line">    instance.ctx = createRenderContext(instance)</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    instance.ctx = &#123; _: instance &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  instance.root = parent ? parent.root : instance</span><br><span class="line">  instance.emit = emit.bind(<span class="literal">null</span>, instance)</span><br><span class="line">  <span class="keyword">return</span> instance</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// ./packages/runtime-core/src/apiCreateApp.ts</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">createAppContext</span>(<span class="params"></span>): <span class="title">AppContext</span> </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    <span class="comment">// ..... 忽略其他属性</span></span><br><span class="line">    <span class="comment">// emptyAppContext中provides默认是个空对象</span></span><br><span class="line">    provides: <span class="built_in">Object</span>.create(<span class="literal">null</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上述代码可以看出，每个组件的<code>provides</code>都是继承自父组件的<code>provides</code>，根组件的<code>provides</code>其实是个空<strong>对象</strong>。</p>
<p>看到这里大致可以猜出来<code>provide/inject</code>是什么了，剩下我们只要了解下<code>provide</code>和<code>inject</code>两个工具函数的原理就能明白其中的缘由了。</p>
<ol start="3">
<li><code>provide</code>方法原理</li>
</ol>
<blockquote>
<p>provide 方法的作用是往当前实例provides写入新的key-value,如果key已存在则覆盖</p>
</blockquote>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">provide</span>&lt;<span class="title">T</span>&gt;(<span class="params">key: InjectionKey&lt;T&gt; | <span class="built_in">string</span> | <span class="built_in">number</span>, value: T</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (!currentInstance) &#123;</span><br><span class="line">    <span class="keyword">if</span> (__DEV__) &#123;</span><br><span class="line">      warn(<span class="string">`provide() can only be used inside setup().`</span>)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> provides = currentInstance.provides</span><br><span class="line">    <span class="keyword">const</span> parentProvides =</span><br><span class="line">      currentInstance.parent &amp;&amp; currentInstance.parent.provides</span><br><span class="line">    <span class="keyword">if</span> (parentProvides === provides) &#123;</span><br><span class="line">      provides = currentInstance.provides = <span class="built_in">Object</span>.create(parentProvides)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// provides 中注入新值, 如果根组件与父组件有相同的key则会被父组件注入的key-value覆盖</span></span><br><span class="line">    provides[key <span class="keyword">as</span> <span class="built_in">string</span>] = value</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="4">
<li><code>inject</code>方法原理</li>
</ol>
<blockquote>
<p>inject 方法的作用是从当前实例的provides获取key对应的value值。</p>
</blockquote>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">inject</span>(<span class="params"></span></span></span><br><span class="line"><span class="function"><span class="params">  key: InjectionKey&lt;<span class="built_in">any</span>&gt; | <span class="built_in">string</span>,</span></span></span><br><span class="line"><span class="function"><span class="params">  defaultValue?: unknown,</span></span></span><br><span class="line"><span class="function"><span class="params">  treatDefaultAsFactory = <span class="literal">false</span></span></span></span><br><span class="line"><span class="function"><span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 当前组件的实例</span></span><br><span class="line">  <span class="keyword">const</span> instance = currentInstance || currentRenderingInstance</span><br><span class="line">  <span class="keyword">if</span> (instance) &#123;</span><br><span class="line">    <span class="comment">// 实例父级的provides；如果组件为根组件，就是自身appContext的provides</span></span><br><span class="line">    <span class="keyword">const</span> provides =</span><br><span class="line">      instance.parent == <span class="literal">null</span></span><br><span class="line">        ? instance.vnode.appContext &amp;&amp; instance.vnode.appContext.provides</span><br><span class="line">        : instance.parent.provides</span><br><span class="line">	<span class="comment">// 判断provides对象中是否存在key属性, 有就返回对应的value</span></span><br><span class="line">    <span class="keyword">if</span> (provides &amp;&amp; (key <span class="keyword">as</span> <span class="built_in">string</span> | symbol) <span class="keyword">in</span> provides) &#123;</span><br><span class="line">      <span class="keyword">return</span> provides[key <span class="keyword">as</span> <span class="built_in">string</span>]</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="built_in">arguments</span>.length &gt; <span class="number">1</span>) &#123;	<span class="comment">// 判断当前函数是否存在第二参数</span></span><br><span class="line">      <span class="comment">// 如果treatDefaultAsFactory为true且第二个参数是个函数, 直接返回这个函数的默认结果, 否则会直接返回第二个参数。</span></span><br><span class="line">      <span class="comment">// 作用：provides中不存在当前key时起到默认值的作用</span></span><br><span class="line">      <span class="keyword">return</span> treatDefaultAsFactory &amp;&amp; isFunction(defaultValue)</span><br><span class="line">        ? defaultValue()</span><br><span class="line">        : defaultValue</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (__DEV__) &#123;</span><br><span class="line">      warn(<span class="string">`injection &quot;<span class="subst">$&#123;<span class="built_in">String</span>(key)&#125;</span>&quot; not found.`</span>)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (__DEV__) &#123;</span><br><span class="line">    warn(<span class="string">`inject() can only be used inside setup() or functional components.`</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>源码总结：子组件继承父组件的<code>provides</code>属性，从而达到深层的组件也能访问到注入组件的数据。</p>
<h2 id="简易版Provide-Inject"><a href="#简易版Provide-Inject" class="headerlink" title="简易版Provide / Inject"></a>简易版Provide / Inject</h2><p>通过上面源码的学习，我们可以自己写一个简易版的<code>Provide / Inject</code>，原理就是es6的class继承，直接附上代码。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Root</span> </span>&#123;</span><br><span class="line">	<span class="keyword">static</span> provides = &#123;&#125;</span><br><span class="line">	<span class="keyword">constructor</span>() &#123;&#125;</span><br><span class="line"> 	provide(key, value) &#123;</span><br><span class="line">		Root.provides[key] = value</span><br><span class="line">	&#125;</span><br><span class="line">	inject(key, defaultValue, treatDefaultAsFactory) &#123;</span><br><span class="line">		<span class="keyword">if</span> (key &amp;&amp; key <span class="keyword">in</span> Root.provides) &#123;</span><br><span class="line">			<span class="keyword">return</span> Root.provides[key]</span><br><span class="line">		&#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="built_in">arguments</span>.length &gt; <span class="number">1</span>) &#123;</span><br><span class="line">			<span class="keyword">return</span> treatDefaultAsFactory &amp;&amp; <span class="keyword">typeof</span> defaultValue === <span class="string">&#x27;function&#x27;</span> ? defaultValue() : defaultValue</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//  继承root</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Parent</span> <span class="keyword">extends</span> <span class="title">Root</span> </span>&#123;</span><br><span class="line">	<span class="keyword">constructor</span>() &#123;</span><br><span class="line">		<span class="built_in">super</span>();</span><br><span class="line">	&#125;</span><br><span class="line">	provide(key, value) &#123;</span><br><span class="line">         <span class="comment">// 重写父类provide，并调用父类provide方法</span></span><br><span class="line">		<span class="built_in">super</span>.provide(key, value)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Child</span> <span class="keyword">extends</span> <span class="title">Parent</span> </span>&#123;</span><br><span class="line">	<span class="keyword">constructor</span>() &#123;</span><br><span class="line">		<span class="built_in">super</span>();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> rootInstance = <span class="keyword">new</span> Root();</span><br><span class="line">rootInstance.provide(<span class="string">&#x27;username&#x27;</span>, <span class="string">&#x27;Yxx&#x27;</span>)</span><br><span class="line"><span class="keyword">let</span> parentInstance = <span class="keyword">new</span> Parent();</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> instance = <span class="keyword">new</span> Child();</span><br><span class="line">parentInstance.provide(<span class="string">&#x27;age&#x27;</span>, <span class="number">18</span>);</span><br><span class="line"><span class="built_in">console</span>.log(instance.inject(<span class="string">&#x27;age&#x27;</span>))</span><br><span class="line"><span class="built_in">console</span>.log(instance.inject(<span class="string">&#x27;username&#x27;</span>))</span><br></pre></td></tr></table></figure>

<h2 id="应用场景（妙用）"><a href="#应用场景（妙用）" class="headerlink" title="应用场景（妙用）"></a>应用场景（妙用）</h2><p>重点来了，了解完原理之后我们来看下<code>Provide / Inject</code>的应用场景，如何来代替现在的状态管理工具<code>Vuex</code>呢？</p>
<ol>
<li>首先创建一个<code>store</code>文件夹（文件夹名称可随意修改）用于存放共享数据相关的代码，并且创建一个入口文件<code>index.ts</code></li>
</ol>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; reactive, <span class="keyword">readonly</span> &#125; <span class="keyword">from</span> <span class="string">&quot;vue&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// interface--导出接口用于变量类型声明(ts专用)</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">interface</span> Store &#123;</span><br><span class="line">  state: &#123;</span><br><span class="line">    count: <span class="built_in">number</span>;</span><br><span class="line">  &#125;,</span><br><span class="line">  increment(): <span class="built_in">void</span>,</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// state--存放需要全局共享的数据。通过reactive创建对象，为了实现响应式，如果直接赋值普通对象或基本类型，则不会有响应式</span></span><br><span class="line"><span class="keyword">const</span> state = reactive(&#123;</span><br><span class="line">  count: <span class="number">0</span>,</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// 修改state的方法，类似于vuex的mutations</span></span><br><span class="line"><span class="keyword">const</span> increment = (): <span class="function"><span class="params">void</span> =&gt;</span> &#123;</span><br><span class="line">  state.count++;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 导出数据和方法。readonly为防止调用方直接修改state</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> <span class="built_in">global</span>: Store = &#123;</span><br><span class="line">  state: <span class="keyword">readonly</span>(state),</span><br><span class="line">  increment,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>然后在根组件(<code>App.vue</code>)注入依赖数据</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&lt;script lang=<span class="string">&quot;ts&quot;</span>&gt;</span><br><span class="line"><span class="keyword">import</span> &#123; defineComponent, getCurrentInstance &#125; <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span></span><br><span class="line"><span class="comment">// 导入store</span></span><br><span class="line"><span class="keyword">import</span> &#123; <span class="built_in">global</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;./store/index&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> defineComponent(&#123;</span><br><span class="line">  name: <span class="string">&#x27;App&#x27;</span>,</span><br><span class="line">  <span class="comment">// 注入依赖数据</span></span><br><span class="line">  provide: &#123;</span><br><span class="line">    <span class="built_in">global</span></span><br><span class="line">  &#125;,</span><br><span class="line">&#125;)</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>

<ol start="3">
<li>最后子组件通过<code>inject</code>获取注入的数据，以及调用相关的方法来修改注入的数据</li>
</ol>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;div <span class="keyword">class</span>=<span class="string">&quot;inject-box&quot;</span>&gt;</span><br><span class="line">    &lt;p&gt;&#123;&#123; <span class="built_in">global</span>.state.count &#125;&#125;&lt;/p&gt;</span><br><span class="line">    &lt;button <span class="meta">@click</span>=<span class="string">&quot;global.increment&quot;</span>&gt;++&lt;/button&gt;</span><br><span class="line">  &lt;/div&gt;</span><br><span class="line">&lt;/template&gt;</span><br><span class="line"></span><br><span class="line">&lt;script lang=<span class="string">&quot;ts&quot;</span>&gt;</span><br><span class="line"><span class="keyword">import</span> &#123; ref, defineComponent&#125; <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> defineComponent(&#123;</span><br><span class="line">  name: <span class="string">&#x27;HelloWorld&#x27;</span>,</span><br><span class="line">  <span class="comment">// 获取注入的数据，模板内可直接通过global.xxxxx调用</span></span><br><span class="line">  inject: [<span class="string">&#x27;global&#x27;</span>],</span><br><span class="line">  setup: <span class="function">() =&gt;</span> &#123;&#125;</span><br><span class="line">&#125;)</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>

<ol start="4">
<li>通过前3步，已经完成了全局状态管理。但是有一个问题，当项目特别庞大，全部的状态数据存在一份代码里面肯定是不合理的。所以接下去再实现下模板化，使状态数据能模块化管理。</li>
<li>创建<code>modules</code>文件夹存放模块数据，并创建<code>user.ts</code></li>
</ol>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; reactive, <span class="keyword">readonly</span> &#125; <span class="keyword">from</span> <span class="string">&quot;vue&quot;</span>;</span><br><span class="line"><span class="comment">// interface</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">interface</span> UserStore &#123;</span><br><span class="line">  state: &#123;</span><br><span class="line">    username: <span class="built_in">string</span>;</span><br><span class="line">  &#125;,</span><br><span class="line">  editUserName(username: <span class="built_in">string</span>): <span class="built_in">void</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// state</span></span><br><span class="line"><span class="keyword">const</span> state = reactive(&#123;</span><br><span class="line">  username: <span class="string">&quot;&quot;</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// 修改state的方法</span></span><br><span class="line"><span class="keyword">const</span> editUserName = <span class="function">(<span class="params">username: <span class="built_in">string</span></span>) =&gt;</span> &#123;</span><br><span class="line">  state.username = username;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> User = reactive(&#123;</span><br><span class="line">  state: <span class="keyword">readonly</span>(state),</span><br><span class="line">  editUserName</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<ol start="6">
<li>在<code>store/index.ts</code>导入<code>user</code>模块</li>
</ol>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 省略部分代码</span></span><br><span class="line"><span class="keyword">import</span> &#123; reactive, <span class="keyword">readonly</span>, toRefs &#125; <span class="keyword">from</span> <span class="string">&quot;vue&quot;</span>;</span><br><span class="line"><span class="comment">// 导入模块</span></span><br><span class="line"><span class="keyword">import</span> &#123; User &#125; <span class="keyword">from</span> <span class="string">&#x27;./modules/user&#x27;</span>;</span><br><span class="line"><span class="comment">// state</span></span><br><span class="line"><span class="keyword">const</span> state = reactive(&#123;</span><br><span class="line">  count: <span class="number">0</span>,</span><br><span class="line">  <span class="comment">// 安装模块数据到state</span></span><br><span class="line">  ...toRefs(User.state)</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> <span class="built_in">global</span>: Store = &#123;</span><br><span class="line">  state: <span class="keyword">readonly</span>(state),</span><br><span class="line">  <span class="comment">// 导出模块暴露的方法</span></span><br><span class="line">  editUserName: User.editUserName</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<ol start="7">
<li>最后我们在子组件调用即可，方法同第3步类型</li>
</ol>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;div <span class="keyword">class</span>=<span class="string">&quot;inject-box&quot;</span>&gt;</span><br><span class="line">    &lt;p&gt;&#123;&#123; <span class="built_in">global</span>.state.count &#125;&#125;&lt;/p&gt;</span><br><span class="line">    &lt;button <span class="meta">@click</span>=<span class="string">&quot;global.increment&quot;</span>&gt;++&lt;/button&gt;</span><br><span class="line">  &lt;/div&gt;</span><br><span class="line">  &lt;div <span class="keyword">class</span>=<span class="string">&quot;inject-box&quot;</span>&gt;</span><br><span class="line">    &lt;p&gt;&#123;&#123; <span class="built_in">global</span>.state.username &#125;&#125;&lt;/p&gt;</span><br><span class="line">    &lt;input <span class="keyword">type</span>=<span class="string">&quot;text&quot;</span> v-model=<span class="string">&quot;uname&quot;</span> /&gt;</span><br><span class="line">  &lt;/div&gt;</span><br><span class="line">&lt;/template&gt;</span><br><span class="line"></span><br><span class="line">&lt;script lang=<span class="string">&quot;ts&quot;</span>&gt;</span><br><span class="line"><span class="keyword">import</span> &#123; ref, defineComponent, inject, watch &#125; <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span></span><br><span class="line"><span class="comment">// 导入变量类型</span></span><br><span class="line"><span class="keyword">import</span> &#123; Store &#125; <span class="keyword">from</span> <span class="string">&#x27;../store/index&#x27;</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> defineComponent(&#123;</span><br><span class="line">  name: <span class="string">&#x27;HelloWorld&#x27;</span>,</span><br><span class="line">  inject: [<span class="string">&#x27;global&#x27;</span>],</span><br><span class="line">  setup: <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> uname = ref(<span class="string">&#x27;&#x27;</span>)</span><br><span class="line">    <span class="comment">// setup 内使用inject方法获取到注入的数据</span></span><br><span class="line">    <span class="keyword">const</span> <span class="built_in">global</span>: Store | <span class="literal">undefined</span> = inject(<span class="string">&#x27;global&#x27;</span>)</span><br><span class="line"></span><br><span class="line">    watch(uname, (newValue: <span class="built_in">string</span>): <span class="function"><span class="params">void</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="comment">// 调用 editUserName 方法修改state里面的username</span></span><br><span class="line">      <span class="built_in">global</span> &amp;&amp; <span class="built_in">global</span>.editUserName(newValue)</span><br><span class="line">    &#125;)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> &#123; uname &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>



<div class="aplayer no-destroy" data-id="热门" data-server="tencent" data-type="search" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-preload="none" data-autoplay="true" muted></div>















































































































</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Tab</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://tabxx.github.io/tab.github.io/2021/05/15/inject/">https://tabxx.github.io/tab.github.io/2021/05/15/inject/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://tabxx.github.io/tab.github.io" target="_blank">Tab</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tab.github.io/tags/Vue/">Vue</a></div><div class="post_share"><div class="social-share" data-image="/tab.github.io/2021/05/15/inject/top.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/tab.github.io/2021/07/08/ssr/"><img class="prev-cover" src= "" data-lazy-src="/tab.github.io/2021/07/08/ssr/ssr.jpg" onerror="onerror=null;src='/tab.github.io/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">性能优化之SSR初体验</div></div></a></div><div class="next-post pull-right"><a href="/tab.github.io/2021/02/23/vue3-reactive-ref/"><img class="next-cover" src= "" data-lazy-src="/tab.github.io/2021/02/23/vue3-reactive-ref/reactive.png" onerror="onerror=null;src='/tab.github.io/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Vue3.0——reactive和ref原理</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/tab.github.io/2019/11/18/computed/" title="computed 实现原理"><img class="cover" src= "" data-lazy-src="/tab.github.io/2019/11/18/computed/topbg.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-11-18</div><div class="title">computed 实现原理</div></div></a></div><div><a href="/tab.github.io/2019/11/11/vue-directive/" title="vue自定义指令的魅力"><img class="cover" src= "" data-lazy-src="/tab.github.io/2019/11/11/vue-directive/2701794-250949a6bda06b20.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-11-11</div><div class="title">vue自定义指令的魅力</div></div></a></div><div><a href="/tab.github.io/2021/02/23/vue3-reactive-ref/" title="Vue3.0——reactive和ref原理"><img class="cover" src= "" data-lazy-src="/tab.github.io/2021/02/23/vue3-reactive-ref/reactive.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-02-23</div><div class="title">Vue3.0——reactive和ref原理</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src= "" data-lazy-src="/tab.github.io/images/avatar.jpg" onerror="this.onerror=null;this.src='/tab.github.io/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">Tab</div><div class="author-info__description">Tab</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/tab.github.io/archives/"><div class="headline">文章</div><div class="length-num">10</div></a></div><div class="card-info-data-item is-center"><a href="/tab.github.io/tags/"><div class="headline">标签</div><div class="length-num">7</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/Tabxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Vue3-0%E2%80%94%E2%80%94Provide-Inject%E7%9A%84%E5%A6%99%E7%94%A8"><span class="toc-number">1.</span> <span class="toc-text">Vue3.0——Provide&#x2F;Inject的妙用</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Provide-Inject"><span class="toc-number">1.1.</span> <span class="toc-text">Provide &#x2F; Inject</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Provide-Inject-%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F"><span class="toc-number">1.2.</span> <span class="toc-text">Provide &#x2F; Inject 使用方式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Provide-Inject-%E5%8E%9F%E7%90%86"><span class="toc-number">1.3.</span> <span class="toc-text">Provide &#x2F; Inject 原理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AE%80%E6%98%93%E7%89%88Provide-Inject"><span class="toc-number">1.4.</span> <span class="toc-text">简易版Provide &#x2F; Inject</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF%EF%BC%88%E5%A6%99%E7%94%A8%EF%BC%89"><span class="toc-number">1.5.</span> <span class="toc-text">应用场景（妙用）</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/tab.github.io/2021/08/09/femonitor/" title="前端异常监控平台"><img src= "" data-lazy-src="/tab.github.io/2021/08/09/femonitor/IMG_2992.jpeg" onerror="this.onerror=null;this.src='/tab.github.io/img/404.jpg'" alt="前端异常监控平台"/></a><div class="content"><a class="title" href="/tab.github.io/2021/08/09/femonitor/" title="前端异常监控平台">前端异常监控平台</a><time datetime="2021-08-09T12:25:00.000Z" title="发表于 2021-08-09 20:25:00">2021-08-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/tab.github.io/2021/07/08/ssr/" title="性能优化之SSR初体验"><img src= "" data-lazy-src="/tab.github.io/2021/07/08/ssr/ssr.jpg" onerror="this.onerror=null;this.src='/tab.github.io/img/404.jpg'" alt="性能优化之SSR初体验"/></a><div class="content"><a class="title" href="/tab.github.io/2021/07/08/ssr/" title="性能优化之SSR初体验">性能优化之SSR初体验</a><time datetime="2021-07-08T06:37:22.000Z" title="发表于 2021-07-08 14:37:22">2021-07-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/tab.github.io/2021/05/15/inject/" title="Vue3.0——Provide/Inject的妙用"><img src= "" data-lazy-src="/tab.github.io/2021/05/15/inject/top.jpg" onerror="this.onerror=null;this.src='/tab.github.io/img/404.jpg'" alt="Vue3.0——Provide/Inject的妙用"/></a><div class="content"><a class="title" href="/tab.github.io/2021/05/15/inject/" title="Vue3.0——Provide/Inject的妙用">Vue3.0——Provide/Inject的妙用</a><time datetime="2021-05-15T15:07:43.000Z" title="发表于 2021-05-15 23:07:43">2021-05-15</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By Tab</div><div class="footer_custom_text">Hi, welcome to my <a href="https://tabxx.github.io/tab.github.io/">blog</a>!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/tab.github.io/js/utils.js"></script><script src="/tab.github.io/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'DCF6gBtqrrJYBofXtoomsqy4-gzGzoHsz',
      appKey: 'e9JXPlIRUQ8XLONSE4dsozQA',
      placeholder: 'Please leave your footprints',
      avatar: 'monsterid',
      meta: 'nick,mail,link'.split(','),
      pageSize: '10',
      lang: 'zh-CN',
      recordIP: false,
      serverURLs: '',
      emojiCDN: '',
      emojiMaps: "",
      enableQQ: false,
      path: window.location.pathname,
      requiredFields: ["nick,mail"],
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !false) {
  if (false) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>